# -*- coding:utf-8 -*-

"""
商家黑名单Service
"""

from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime

from module_admin.dao.seller_blacklist_dao import SellerBlacklistDao
from module_admin.entity.do.seller_blacklist_do import SellerBlacklist
from utils.log_util import logger


class SellerBlacklistService:
    """商家黑名单业务逻辑层"""
    
    @classmethod
    async def get_list(cls, db: AsyncSession, query_dict: dict = None, user_id: int = None):
        """
        获取商家黑名单列表（按用户隔离）
        
        Args:
            db: 数据库会话
            query_dict: 查询条件字典
            user_id: 用户ID，如果提供则只获取该用户的黑名单
        """
        return await SellerBlacklistDao.get_list(db, query_dict, user_id=user_id)
    
    @classmethod
    async def get_by_id(cls, db: AsyncSession, blacklist_id: int):
        """
        根据ID获取商家黑名单
        """
        return await SellerBlacklistDao.get_by_id(db, blacklist_id)
    
    @classmethod
    async def add(cls, db: AsyncSession, blacklist_data: dict):
        """
        新增商家黑名单
        
        Args:
            blacklist_data: {
                'seller_id': '卖家ID',
                'seller_nick': '卖家昵称',
                'reason': '拉黑原因',
                'remark': '备注'
            }
        """
        # ✅ 检查是否已存在（seller_id或seller_nick任意一个匹配就认为已存在）
        seller_id = blacklist_data.get('seller_id')
        seller_nick = blacklist_data.get('seller_nick')
        
        if not seller_id and not seller_nick:
            raise ValueError("卖家ID和卖家昵称至少需要填写一个")
        
        # ✅ 获取用户ID（从blacklist_data或create_by字段）
        user_id = blacklist_data.get('create_by')
        if user_id:
            try:
                user_id = int(user_id)
            except (ValueError, TypeError):
                user_id = None
        
        exists = await SellerBlacklistDao.check_exists(
            db,
            seller_id=seller_id,
            seller_nick=seller_nick,
            user_id=user_id
        )
        
        if exists:
            raise ValueError("该商家已在黑名单中")
        
        # ✅ 修复：create_by和dept_id应该是Integer类型，不能是空字符串
        create_by = blacklist_data.get('create_by')
        dept_id = blacklist_data.get('dept_id')
        
        if create_by is None or create_by == '':
            create_by = 1  # 默认管理员ID
        else:
            create_by = int(create_by)
        
        if dept_id is None or dept_id == '':
            dept_id = 1  # 默认部门ID
        else:
            dept_id = int(dept_id)
        
        blacklist = SellerBlacklist(
            seller_id=blacklist_data.get('seller_id'),
            seller_nick=blacklist_data.get('seller_nick'),
            reason=blacklist_data.get('reason'),
            remark=blacklist_data.get('remark'),
            status=blacklist_data.get('status', '0') or '0',  # ✅ 添加status字段，默认'0'（启用）
            create_by=create_by,
            dept_id=dept_id,
            create_time=datetime.now(),
            del_flag='0'
        )
        
        await SellerBlacklistDao.add(db, blacklist)
        await db.commit()
        
        logger.info(f"添加商家黑名单: {blacklist_data.get('seller_nick')} ({blacklist_data.get('seller_id')})")
        return blacklist
    
    @classmethod
    async def update(cls, db: AsyncSession, blacklist_id: int, update_data: dict):
        """
        更新商家黑名单
        """
        update_data['update_time'] = datetime.now()
        await SellerBlacklistDao.update(db, blacklist_id, update_data)
        await db.commit()
        
        logger.info(f"更新商家黑名单: ID={blacklist_id}")
    
    @classmethod
    async def delete(cls, db: AsyncSession, blacklist_id: int):
        """
        删除商家黑名单
        """
        await SellerBlacklistDao.delete(db, blacklist_id)
        await db.commit()
        
        logger.info(f"删除商家黑名单: ID={blacklist_id}")
    
    @classmethod
    async def batch_delete(cls, db: AsyncSession, blacklist_ids: list):
        """
        批量删除商家黑名单
        """
        for blacklist_id in blacklist_ids:
            await SellerBlacklistDao.delete(db, blacklist_id)
        
        await db.commit()
        logger.info(f"批量删除商家黑名单: {len(blacklist_ids)}条")
    
    @classmethod
    async def add_from_search_result(cls, db: AsyncSession, item_data: dict, user_id: str = ''):
        """
        从搜索结果直接拉黑商家
        
        Args:
            item_data: {
                'seller_id': '卖家ID',
                'seller_nick': '卖家昵称'
            }
        """
        blacklist_data = {
            'seller_id': item_data.get('seller_id'),
            'seller_nick': item_data.get('seller_nick'),
            'reason': '从搜索结果拉黑',
            'create_by': user_id
        }
        
        return await cls.add(db, blacklist_data)

